package daosimp;

import java.util.ArrayList;
import java.util.List;

import modelo.Persona;
import modelo.Sesion;

import org.hibernate.Query;
import org.hibernate.Transaction;

import util1.HibernateUtil;
import daos.SesionDAO;

public class SesionDAOIMP implements SesionDAO {

	private Transaction tx;

	@Override
	public void registrarSesion(Sesion sesion) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.save(sesion);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public List<Sesion> listarTotalSesiones() {
		List<Sesion> sesiones = new ArrayList<Sesion>();
		try {
			tx = HibernateUtil.session.beginTransaction();
			String hql = "FROM Sesion";
			Query query = HibernateUtil.session.createQuery(hql);
			if (!query.list().isEmpty()) {
				sesiones = query.list();
			}
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
		}
		return sesiones;
	}

	@Override
	public void modificarSesion(Sesion sesion) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.update(sesion);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public void eliminarSesion(Sesion sesion) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.delete(sesion);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public Sesion buscarSesionxPersona(Persona persona) {
		Sesion sesion = null;
		try {
			tx = HibernateUtil.session.beginTransaction();
			String hql = "FROM Sesion where idPersona ='"
					+ persona.getIdPersona() + "'";
			Query query = HibernateUtil.session.createQuery(hql);
			if (!query.list().isEmpty()) {
				sesion = (Sesion) query.list().get(0);
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		}
		return sesion;
	}

}
